package org.thanos.demo.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.thanos.demo.service.FileService;


@RestController
public class FileController {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private FileService fileService;

    /**
     * 保存文件
     *
     * @param file
     * @param response
     */
    @PostMapping("/uploadFile")
    public void uploadFile(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
        try {
            fileService.uploadFile(file);
            response.setStatus(HttpStatus.OK.value());
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
    }

    /**
     * 查看文件
     *
     * @param fileName
     * @param response
     */
    @GetMapping(value = "/readImageFile")
    public void readImageFile(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            fileService.downloadFile(fileName, response);
            response.setStatus(HttpStatus.OK.value());
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
    }
}
